package com.cn.rocketmq.producer.producer;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.cn.rocketmq.producer.enums.MQEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class ProducerTemplate {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 测试用的，实际生产一般不用这种
     *
     * @param topic
     * @param body
     * @return
     */
    @Deprecated
    public String sendMsgByTopic(String topic, String body) {
        rocketMQTemplate.convertAndSend(topic, body);
        return MQEnum.SUCCESS.getMsg();
    }

    /**
     * 测试用的，实际生产不这样发
     *
     * @param topic
     * @param msgBody
     * @param timeout    millis
     * @param delayLevel 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
     * @return
     */
    @Deprecated
    public String sendDelayMsg(String topic, String msgBody, long timeout, int delayLevel) {
        Message<String> message = MessageBuilder.withPayload(msgBody).build();
        SendResult sendResult = rocketMQTemplate.syncSend(topic, message, timeout, delayLevel);
        return String.valueOf(sendResult.getSendStatus());
    }


    /**
     * 发送带topic的消息
     *
     * @param topic
     * @param tag
     * @param msgBody
     * @param key
     * @param delayLevel 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
     * @return
     */
    public String sendMsgWithTag(String topic, String tag, String msgBody, String key, int delayLevel) {
        if (StrUtil.isBlank(key)) {
            key = IdUtil.fastSimpleUUID();
        }
        org.apache.rocketmq.common.message.Message message = new org.apache.rocketmq.common.message.Message(topic, tag, key, msgBody.getBytes(StandardCharsets.UTF_8));
        if (delayLevel > 0) {
            message.setDelayTimeLevel(delayLevel);
        }
        SendResult sendResult = new SendResult();
        try {
            sendResult = rocketMQTemplate.getProducer().send(message);
        } catch (Exception e) {
            log.info("发送失败: " + e);
        }
        return String.valueOf(sendResult.getSendStatus());
    }

    public String sendMsgWithTag(String topic, String tag, String msgBody) {
        return this.sendMsgWithTag(topic, tag, msgBody, null, 0);
    }

    public String sendDelayMsgWithTag(String topic, String tag, String msgBody, int delayLevel) {
        return this.sendMsgWithTag(topic, tag, msgBody, null, delayLevel);
    }

}
